﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using WebBrowserTest.AnalyzeResults;
using HtmlAgilityPack;

namespace WebBrowserTest.Analyzers
{
    public class WebarchiveAnalyzer : AbstractAnalyzer
    {
        private HtmlDocument _htmlDoc = new HtmlDocument();
        public WebarchiveAnalyzer()
        {
            _lookupExpr = "<a href=\\\"http://web.archive.org/we/\\d+\\/http:.+\\\"*>([^<]+)<\\/a>";
        }


        public override AbstractAnalyzeResult GetAnalyseResult(string html, string url)
        {
            string domainAge = "--";
            _htmlDoc.LoadHtml(html);
            Regex expr = new Regex(@"(\w+\d+,{1}\s+)+");
            var anchorNodes = _htmlDoc.DocumentNode.SelectNodes("//a");
            if (anchorNodes != null)
            {
                var anchors = anchorNodes.Where(o => o.Attributes["href"] != null &&
                                                     o.Attributes["href"].Value.Contains("http://web.archive.org/web/"))
                    .Where(x => x.InnerText.Contains(",")).ToList(); // &&
                //expr.IsMatch(o.InnerText)).ToList();)
                if (anchors.Count > 0)
                {
                    var values = anchors[0].InnerText.Split(' ');
                    if (values.Count() == 3)
                    {
                        DateTime pageDate =
                            DateTime.Parse(string.Format("{0} {1} {2}", values[2], values[0], values[1].Replace(",", "")));
                        TimeSpan age = DateTime.Now.Subtract(pageDate);
                        domainAge = string.Format("{0}", (int)age.Days/365);
                    }
                }
            }
            return new DomainAgeAnalyzeResults{ DomainAge = domainAge, DomainName = url, Date = DateTime.Now };
        }
    }
}
